package ar.com.duam.porky.movil.tasks;

import static ar.com.duam.porky.movil.ConstantesPorky.DATE_PATTERN;
import static ar.com.duam.porky.movil.ConstantesPorky.ENCODING_ISO_8859_1;
import static ar.com.duam.porky.movil.ConstantesPorky.ENCODING_UTF_8;
import static ar.com.duam.porky.movil.ConstantesPorky.URL_PORKY;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;

import android.os.AsyncTask;
import android.util.Log;
import ar.com.duam.porky.movil.Movimiento;

public class SubirMovimientosTask extends AsyncTask<Movimiento, Void, Boolean> 
{

	@Override
	protected Boolean doInBackground(Movimiento... params) 
	{
		HttpURLConnection urlConnection = null;
		String response = "";
		Movimiento movimiento = params[0];

		try 
		{
			SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN);
			String encoding = ENCODING_ISO_8859_1;
			
			String datos = URLEncoder.encode(Movimiento.COLUMN_CONCEPTO_ID, encoding) +"="+ URLEncoder.encode(movimiento.getConceptoId().toString(), encoding);
			datos += "&"+ URLEncoder.encode(Movimiento.COLUMN_FECHA, encoding) +"="+ URLEncoder.encode(sdf.format(movimiento.getFecha()), encoding);
			datos += "&"+ URLEncoder.encode(Movimiento.COLUMN_DETALLE, encoding) +"="+ URLEncoder.encode(movimiento.getDetalle(), encoding);
			datos += "&"+ URLEncoder.encode(Movimiento.COLUMN_IMPORTE, encoding) +"="+ URLEncoder.encode(movimiento.getImporte().toString(), encoding);
			
			Log.d("subir_movimiento", "Enviando los datos ["+ datos +"]");
			URL url = new URL(URL_PORKY +"/ws/movimientos");
			Log.d("subir_movimiento", "Conect�ndose a "+ URL_PORKY +"/ws/movimientos");
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setDoOutput(true);
			
			OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
			writer.write(datos);
			writer.flush();
			Log.d("subir_movimiento", "Datos enviados");
			
			BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), ENCODING_UTF_8));
			String line;
			
			while ((line = reader.readLine()) != null)
			{
				Log.d("subir_movimiento", "Se recibi� ["+ line +"]");
				response += line;
			}
			
			writer.close();
			reader.close();
		}
		catch (Exception ex)
		{
			Log.e("syncro", "Error descargando conceptos", ex);
		}
		finally 
		{
			urlConnection.disconnect();
		}
		
		return !response.toLowerCase().contains("error");
	}

}
